<template>
  <!-- 采购单据制作 -->
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="24" :xs="24">
        <el-form
            ref="orderRef"
          :inline="true"
          :model="form"
          :rules="rules"
            label-width="100px"
        >
          <el-form-item label="系统单号" prop="systematicReceipt">
            <el-input
              v-model="form.systematicReceipt"
              class="form-item"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="单据类型" prop="receiptType">
            <el-radio-group v-model="form.receiptType" class="form-item">
              <el-radio-button
                  v-hasPermi="['purchase:purchaseReceiptProcessing:warehousing']"
                  :value="1"
                label="1"
                @change="warehouse"
                >采购入库</el-radio-button
              >
              <el-radio-button
                  v-hasPermi="['purchase:purchaseReceiptProcessing:retreat']"
                  :value="2"
                label="2"
                @change="retreat"
                >采购退库</el-radio-button
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="单据状态" prop="receiptStatus">
            <el-radio-group v-model="form.receiptStatus" class="form-item">
              <el-radio-button :value="1" label="1">待审核</el-radio-button>
              <el-radio-button :disabled="takeEffect" :value="2" label="2"
                >已审核</el-radio-button
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="开单日期" prop="invoiceDate">
            <el-date-picker
              v-model="form.invoiceDate"
              format="YYYY/MM/DD"
              placeholder="请选择开单日期"
              type="date"
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
          <el-form-item v-if="retrieval" label="调出仓库" prop="retrievalIds">
            <el-select
              v-model="form.retrievalIds"
              :loading="loading"
              :remote-method="remoteWarehouse"
              class="form-item"
              clearable
              filterable
              placeholder="请输入仓库"
              remote
              remote-show-suffix
            >
              <el-option
                v-for="item in warehouseOptions"
                :key="item.warehouseId"
                :label="item.warehouseName"
                :value="item.warehouseId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
              v-if="warehousing"
            label="调入仓库"
            prop="warehousingIds"
          >
            <el-select
              v-model="form.warehousingIds"
              :loading="loading"
              :remote-method="remoteWarehouse"
              class="form-item"
              clearable
              filterable
              placeholder="请输入仓库"
              remote
              remote-show-suffix
            >
              <el-option
                v-for="item in warehouseOptions"
                :key="item.warehouseId"
                :label="item.warehouseName"
                :value="item.warehouseId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
              v-hasPermi="['purchase:purchaseReceiptProcessing:selectUser']"
            label="经手人"
            prop="userIds"
          >
            <el-select
                v-model="form.userIds"
              class="form-item"
                clearable
              filterable
                placeholder="请选择"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="供应商" prop="supplierIds">
            <el-select
              v-model="form.supplierIds"
              :loading="loading"
              :remote-method="remoteSupplier"
              class="form-item"
              clearable
              filterable
              placeholder="请输入供应商"
              remote
              remote-show-suffix
            >
              <el-option
                v-for="item in supplierOptions"
                :key="item.supplierId"
                :label="item.supplierName"
                :value="item.supplierId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="原始单号" prop="originalReceipt">
            <el-input
              v-model="form.originalReceipt"
              class="form-item"
              clearable
            />
          </el-form-item>
          <el-form-item label="计划单号" prop="planReceipt">
            <el-input v-model="form.planReceipt" class="form-item" clearable />
          </el-form-item>
          <el-form-item label="备注" prop="receiptNotes">
            <el-input
              v-model="form.receiptNotes"
              class="form-item"
              type="textarea"
            />
          </el-form-item>
          <el-form-item label="定金" prop="deposit">
            <el-input
              v-model="form.deposit"
              class="form-item"
              clearable
              oninput="value=value.replace(/[^0-9.]/g,'').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
            />
          </el-form-item>
          <el-form-item label="总金额" prop="totalAmount">
            <el-input
              v-model="form.totalAmount"
              :formatter="
                (value) => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
              "
              :parser="(value) => value.replace(/\￥\s?|(,*)/g, '')"
              class="form-item"
              disabled="disabled"
            />
          </el-form-item>
          <el-form-item label="总金额(大写)" prop="capitalizeTotalAmount">
            <el-input
              v-model="form.capitalizeTotalAmount"
              class="form-item"
              disabled="disabled"
            />
          </el-form-item>
          <div v-if="finding">
            <el-divider />
            <el-form-item
                :disabled="['purchase:purchaseReceiptProcessing:takeEffect']"
              label="审核结果"
              prop="findingOfAudit"
            >
              <el-select
                v-model="form.findingOfAudit"
                class="form-item"
                clearable
                filterable
              >
                <el-option
                  v-for="dict in finding_of_audit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
                :disabled="['purchase:purchaseReceiptProcessing:takeEffect']"
              label="审核意见"
              prop="reviewComments"
            >
              <el-input
                v-model="form.reviewComments"
                clearable
                style="width: 530px"
              />
            </el-form-item>
          </div>
        </el-form>
        <div>
          <div>
            <el-row :gutter="10">
              <el-col :span="1.5">
                <div>货品明细</div>
              </el-col>
            </el-row>
          </div>
          <div>
            <el-table
                :data="form.details"
                :summary-method="getSummaries"
              border
              show-summary
            >
              <el-table-column
                align="center"
                label="序号"
                type="index"
                width="60"
              />
              <el-table-column
                  align="center"
                label="货品编号"
                prop="productCode"
                width="180"
              >
                <template #default="scope">
                  <el-select
                    v-model="scope.row.productCode"
                    :loading="loading"
                    :remote-method="remoteProductCode"
                    filterable
                    placeholder="请输入货品编号"
                    remote
                    remote-show-suffix
                    @change="changeProduct(scope.$index, scope.row)"
                  >
                    <el-option
                      v-for="item in productOptions"
                      :key="item.productId"
                      :label="item.productCode"
                      :value="item.productId"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="货品名称"
                prop="productName"
                width="300"
              >
                <template #default="scope">
                  <el-select
                    v-model="scope.row.productName"
                    :loading="loading"
                    :remote-method="remoteProductName"
                    filterable
                    placeholder="请输入货品名称"
                    remote
                    remote-show-suffix
                    @change="changeProduct(scope.$index, scope.row)"
                  >
                    <el-option
                      v-for="item in productOptions"
                      :key="item.productId"
                      :label="item.productName"
                      :value="item.productId"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="类型"
                prop="productTypeName"
              />
              <el-table-column
                  align="center"
                label="规格"
                prop="productSpecifications"
                width="100"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.productSpecifications"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="单位" prop="measureUnit">
                <template #default="scope">
                  <el-input v-model="scope.row.measureUnit"></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="产地" prop="producer"/>
              <el-table-column
                  align="center"
                label="库存数量"
                prop="inventoryQty"
              />
              <el-table-column
                align="center"
                label="数量"
                prop="planQuantity"
                width="100"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.planQuantity"
                    oninput="value=value.replace(/[^0-9.]/g,'').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2')"
                    @change="calculateDetails(scope.row)"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="单价"
                prop="univalence"
                width="150"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.univalence"
                    oninput="value=value.replace(/[^0-9.]/g,'').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
                    @change="calculateDetails(scope.row)"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="折扣"
                prop="discount"
                width="80"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.discount"
                    oninput="value=value.replace(/[^0-9.]/g,'').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
                    @change="calculateDetails(scope.row)"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                  align="center"
                label="金额"
                prop="money"
                width="150"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.money"
                    oninput="value=value.replace(/[^0-9.]/g,'').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="成本"
                prop="cost"
                width="150"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.cost"
                    oninput="value=value.replace(/[^0-9.]/g,'').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="备注" width="180">
                <template #default="scope">
                  <el-input v-model="scope.row.remarks"></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" fixed="right" label="操作">
                <template #default="scope">
                  <el-button
                    plain
                    round
                    type="danger"
                    @click="form.details.splice(scope.$index, 1)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-affix :offset="20" class="tc mt16 footer" position="bottom">
            <el-button
                v-hasPermi="['purchase:purchaseReceiptProcessing:add']"
              color="#BB5500"
              icon="Plus"
              round
              @click="addOrder"
              >新增单据</el-button
            >
            <el-button
                v-hasPermi="['purchase:purchaseReceiptProcessing:detail']"
              color="#00AAAA"
              icon="CirclePlus"
              round
              @click="addItem"
              >添加明细</el-button
            >
            <el-button
                v-hasPermi="['baseDate:supplier:add']"
              icon="Upload"
              round
                type="success"
              @click="supplierAdd"
              >新增供应商</el-button
            >
            <el-button
                v-hasPermi="['baseDate:product:add']"
              icon="Upload"
              round
                type="warning"
              @click="handleAdd"
              >新增货品</el-button
            >
            <el-button
                v-hasPermi="['purchase:purchaseReceiptProcessing:save']"
              icon="position"
              round
                type="primary"
                @click="submitForm"
              >保存单据</el-button
            >
            <el-button
                v-hasPermi="['purchase:purchaseReceiptProcessing:takeEffect']"
                :disabled="takeEffectBtn"
              icon="Check"
              round
                type="success"
                @click="takeEffectForm"
              >审核单据</el-button
            >
            <el-button
                v-hasPermi="['purchase:purchaseReceiptProcessing:printOut']"
                :disabled="printBtn"
              color="#626aef"
              icon="Printer"
              round
                @click="printOut"
              >打印单据</el-button
            >
            <el-tooltip
              class="box-item"
              content="删除单据，重新制作"
              placement="top"
            >
              <el-button
                  ref="ref22"
                  v-hasPermi="['purchase:purchaseReceiptProcessing:delete']"
                  :disabled="printBtn"
                icon="delete"
                round
                  type="danger"
                  @click="deleteReceipt"
                >删除单据</el-button
              >
            </el-tooltip>
            <el-tooltip
              class="box-item"
              content="取消制作，返回查询"
              placement="top"
            >
              <el-button icon="close" round type="info" @click="cancel"
                >取消制作</el-button
              >
            </el-tooltip>
          </el-affix>
        </div>
      </el-col>
    </el-row>
  </div>

  <!-- 添加供应商配置对话框 -->
  <el-dialog
      v-model="openSupplier"
    :title="titleSupplier"
      append-to-body
    width="700px"
  >
    <el-form
        ref="supplierRef"
      :model="supplierForm"
      :rules="rules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="供应商编号" prop="supplierCode">
            <el-input
              v-model="supplierForm.supplierCode"
              maxlength="30"
              placeholder="请输入供应商编号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input
              v-model="supplierForm.supplierName"
              maxlength="30"
              placeholder="请输入供应商名称"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="业务员" prop="supplierSalesPerson">
            <el-input
              v-model="supplierForm.supplierSalesPerson"
              maxlength="30"
              placeholder="请输入业务员"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="supplierContacts">
            <el-input
              v-model="supplierForm.supplierContacts"
              maxlength="30"
              placeholder="请输入联系人"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="supplierContactNumber">
            <el-input
              v-model="supplierForm.supplierContactNumber"
              maxlength="30"
              placeholder="请输入联系电话"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮编" prop="supplierPostalCode">
            <el-input
              v-model="supplierForm.supplierPostalCode"
              maxlength="30"
              placeholder="请输入邮编"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="期初欠款" prop="supplierOpeningDebt">
            <el-input
              v-model="supplierForm.supplierOpeningDebt"
              maxlength="30"
              placeholder="请输入期初欠款"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户银行" prop="supplierOpeningBank">
            <el-input
              v-model="supplierForm.supplierOpeningBank"
              maxlength="30"
              placeholder="请输入开户银行"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="银行账号" prop="supplierAccountNumber">
            <el-input
              v-model="supplierForm.supplierAccountNumber"
              maxlength="30"
              placeholder="请输入银行账号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纳税号" prop="supplierTaxId">
            <el-input
              v-model="supplierForm.supplierTaxId"
              maxlength="30"
              placeholder="请输入纳税号"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="公司主页" prop="supplierCompanyHomepage">
            <el-input
              v-model="supplierForm.supplierCompanyHomepage"
              maxlength="30"
              placeholder="请输入公司主页"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="supplierEmail">
            <el-input
              v-model="supplierForm.supplierEmail"
              maxlength="30"
              placeholder="请输入电子邮箱"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="公司法人" prop="supplierLegalPerson">
            <el-input
              v-model="supplierForm.supplierLegalPerson"
              maxlength="30"
              placeholder="请输入公司法人"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="supplierForm.status"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="单位地址" prop="supplierWorkAddress">
            <el-input
              v-model="supplierForm.supplierWorkAddress"
              placeholder="请输入单位地址"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              v-model="supplierForm.remarks"
              placeholder="请输入备注"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitSupplierForm">确 定</el-button>
        <el-button @click="cancelSupplierForm">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 添加货品配置对话框 -->
  <el-dialog v-model="open" :title="title" append-to-body width="600px">
    <el-form
        ref="productRef"
      :model="productForm"
      :rules="rules"
      label-width="80px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="货品编号" prop="productCode">
            <el-input
              v-model="productForm.productCode"
              maxlength="30"
              placeholder="请输入货品编号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="货品名称" prop="productName">
            <el-input
              v-model="productForm.productName"
              maxlength="30"
              placeholder="请输入货品名称"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="货品类型" prop="productType">
            <el-tree-select
              v-model="productForm.productType"
              :data="typeOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              check-strictly
              placeholder="请选择货品类型"
              value-key="id"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="货品规格" prop="productSpecifications">
            <el-input
              v-model="productForm.productSpecifications"
              maxlength="30"
              placeholder="请输入货品规格"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="计量单位" prop="measureUnit">
            <el-input
              v-model="productForm.measureUnit"
              maxlength="30"
              placeholder="请输入计量单位"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="货品条码" prop="productBarcode">
            <el-input
              v-model="productForm.productBarcode"
              maxlength="30"
              placeholder="请输入货品条码"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="产地" prop="producer">
            <el-input
              v-model="productForm.producer"
              maxlength="30"
              placeholder="请输入产地"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="成本价" prop="costPrice">
            <el-input
              v-model="productForm.costPrice"
              maxlength="30"
              placeholder="请输入成本价"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="参考售价" prop="univalence">
            <el-input
              v-model="productForm.univalence"
              maxlength="30"
              placeholder="请输入参考售价"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="销售折扣" prop="discount">
            <el-input
              v-model="form.discount"
              maxlength="30"
              placeholder="请输入销售折扣"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库存数量" prop="costPrice">
            <el-input
              v-model="form.inventoryQty"
              disabled
              placeholder="系统自动计算"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="库存上限" prop="upperLimit">
            <el-input
              v-model="productForm.upperLimit"
              maxlength="30"
              placeholder="请输入库存上限"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库存下限" prop="lowerLimit">
            <el-input
              v-model="productForm.lowerLimit"
              maxlength="30"
              placeholder="请输入库存下限"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="默认仓库" prop="defaultWarehouse">
            <el-input
              v-model="productForm.defaultWarehouse"
              maxlength="30"
              placeholder="请输入默认仓库"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="productForm.status">
              <el-radio
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              v-model="productForm.notes"
              placeholder="请输入内容"
              type="textarea"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitProductForm">确 定</el-button>
        <el-button @click="cancelProductForm">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script name="PurchaseDocumentProcessing" setup>
import {getToken} from "@/utils/auth";
import {useRouter} from "vue-router";
import {getUserProfile, listUser} from "@/api/system/user";
import {addSupplier, listSupplier} from "@/api/basedate/supplier";
import {listWarehouse} from "@/api/basedate/warehouse";
import {addProduct, listProduct, productTypeTreeSelect,} from "@/api/basedate/product";
import {delPurchaseReceipt, getPurchaseOrder, savePurchaseReceipt,} from "@/api/purchase/purchaseDocumentProcessing";
import {viewUrl} from "@/api/jimu/jiMuReport";
import {randomId} from "@/utils/RandomUtils";
import RMBConverter from "@/utils/RMBConverter";
import {ref} from "vue";

const { proxy } = getCurrentInstance();
const { finding_of_audit } = proxy.useDict("finding_of_audit");
const { print_selected_files } = proxy.useDict("print_selected_files");
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const { print_selected_sizes } = proxy.useDict("print_selected_sizes");

// 订单状态下拉框
const takeEffect = ref(false);
const takeEffectBtn = ref(false);
const finding = ref(false);
const retrieval = ref(false);
const warehousing = ref(true);
const loading = ref(false);
const printBtn = ref(false);
const router = useRouter();
const printOptions = ref(undefined);
const openUrl = ref("");
// 窗口标题
const title = ref("");
const open = ref(false);
const openSupplier = ref(false);
const titleSupplier = ref("");

const data = reactive({
  userOptions: undefined,
  supplierOptions: undefined,
  warehouseOptions: undefined,
  productOptions: undefined,
  typeOptions: undefined,
  option: {
    warehouseId: undefined,
    warehouseName: undefined,
    supplierId: undefined,
    supplierName: undefined,
    customerId: undefined,
    customerName: undefined,
    productCode: undefined,
    productName: undefined,
    pageSize: 50,
  },
  supplierForm: {
    supplierCode: undefined,
    supplierName: undefined,
    supplierSalesPerson: undefined,
    supplierContacts: undefined,
    supplierContactNumber: undefined,
    supplierWorkAddress: undefined,
    supplierPostalCode: undefined,
    supplierOpeningDebt: undefined,
    supplierOpeningBank: undefined,
    supplierAccountNumber: undefined,
    supplierTaxId: undefined,
    supplierCompanyHomepage: undefined,
    supplierEmail: undefined,
    supplierLegalPerson: undefined,
    status: undefined,
    remarks: undefined,
  },
  productForm: {
    productCode: undefined,
    productName: undefined,
    productType: undefined,
    productSpecifications: undefined,
    measureUnit: undefined,
    producer: undefined,
    costPrice: undefined,
    univalence: undefined,
    productBarcode: undefined,
    upperLimit: undefined,
    lowerLimit: undefined,
    defaultWarehouse: undefined,
    notes: undefined,
    status: undefined,
  },
  // 表单参数
  form: {
    details: [],
    systematicReceipt: null,
    originalReceipt: null,
    receiptType: null,
    receiptCategory: 1,
    receiptStatus: null,
    retrievalIds: null,
    warehousingIds: null,
    supplierIds: null,
    userIds: null,
    invoiceDate: null,
    planReceipt: null,
    receiptNotes: null,
    deposit: null,
    totalAmount: null,
    capitalizeTotalAmount: null,
    findingOfAudit: null,
    reviewComments: null,
    // 采购订单
    systematicOrderForm: null,
    originalOrderForm: null,
    orderFormType: 1,
    orderFormStatus: 2,
    deliveryDate: null,
    orderFormNotes: null,
    orderFormAmount: null,
    orderCapitalizeAmount: null,
    // 打印ID
    printId: null,
    printSize: undefined,
  },
  // 表单校验
  rules: {
    receiptType: [
      { required: true, message: "单据类型不能不选", trigger: "blur" },
    ],
    warehousingIds: [
      { required: true, message: "调入仓库不能为空", trigger: "blur" },
    ],
    retrievalIds: [
      { required: true, message: "调出仓库不能为空", trigger: "blur" },
    ],
    userIds: [{ required: true, message: "经手人不能为空", trigger: "blur" }],
    supplierIds: [
      { required: true, message: "供应商不能为空", trigger: "blur" },
    ],
    deliveryDate: [
      { required: true, message: "开单日期不能为空", trigger: "blur" },
    ],
    supplierCode: [
      { required: true, message: "供应商编号不能为空", trigger: "blur" },
      { max: 30, message: "供应商编号长度不能大于 30 ", trigger: "blur" },
    ],
    supplierName: [
      { required: true, message: "供应商名称不能为空", trigger: "blur" },
      { max: 30, message: "供应商名称长度不能大于 30 ", trigger: "blur" },
    ],
    status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
    supplierEmail: [
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur", "change"],
      },
    ],
    supplierContactNumber: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    productCode: [
      { required: true, message: "货品编号不能为空", trigger: "blur" },
    ],
    productName: [
      { required: true, message: "货品名称不能为空", trigger: "blur" },
    ],
    productType: [
      { required: true, message: "货品类型不能为空", trigger: "blur" },
    ],
    measureUnit: [
      { required: true, message: "计量单位不能为空", trigger: "blur" },
    ],
  },
});

const {
  userOptions,
  supplierOptions,
  warehouseOptions,
  productOptions,
  typeOptions,
  option,
  supplierForm,
  productForm,
  form,
  rules,
} = toRefs(data);

function initialization() {
  const { systematicReceipt } = proxy.$route.query;
  if (systematicReceipt) {
    loadDetail(systematicReceipt);
  } else {
    reset();
    takeEffect.value = true;
    takeEffectBtn.value = true;
    printBtn.value = true;
  }
}
function getNowTime() {
  const now = new Date();
  return now.toLocaleDateString('en-CA');
}
async function getList() {
  option.value.pageSize = 500;
  listUser(option.value).then((response) => {
    userOptions.value = response.rows;
  });
  getUserProfile().then((response) => {
    form.value.userIds = response.data.userId;
  });
  optionReset();
}
/** 新增按钮操作 */
async function addOrder() {
  await router.push({ path: "/index" });
  router.push({ path: "/purchase/purchaseDocumentProcessing" });
}
/** 采购入库 */
function warehouse() {
  form.value.systematicReceipt = "CR-" + randomId();
  retrieval.value = false;
  warehousing.value = true;
}
/** 采购退库 */
function retreat() {
  form.value.systematicReceipt = "CT-" + randomId();
  retrieval.value = true;
  warehousing.value = false;
}
/** 统计金额和成本 */
function calculateDetails(row) {
  row.money = row.cost = Number(
    Math.abs(row.planQuantity) * row.univalence * row.discount
  ).toFixed(2);
}
/** 取消按钮 */
function cancel() {
  router.push({ path: "/purchase/purchaseDocumentQuery" });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(async (valid) => {
    if (form.value.details.length === 0) {
      proxy.$modal.msgError("货品明细不能为空");
    } else if (valid) {
      const details = form.value.details.map((it) => {
        return {
          systematicOrderForm: form.value.systematicOrderForm,
          systematicReceipt: form.value.systematicReceipt,
          productId: it.productId,
          retrievalId: form.value.retrievalIds,
          warehouseId: form.value.warehousingIds,
          supplierId: form.value.supplierIds,
          productSpecifications: it.productSpecifications,
          measureUnit: it.measureUnit,
          planQuantity: it.planQuantity,
          univalence: it.univalence,
          discount: it.discount,
          money: it.money,
          cost: it.cost,
          remarks: it.remarks,
        };
      });
      const reqs = { ...form.value, details };
      await savePurchaseReceipt(reqs);
      proxy.$modal.msgSuccess("采购单据保存成功");
      cancel();
    }
  });
}
/** 审核按钮 */
function takeEffectForm() {
  proxy.$refs["orderRef"].validate(async (valid) => {
    if (form.value.details.length == 0) {
      proxy.$modal.msgError("货品明细不能为空");
    } else if (valid) {
      const details = form.value.details.map((it) => {
        return {
          systematicOrderForm: form.value.systematicOrderForm,
          systematicReceipt: form.value.systematicReceipt,
          productId: it.productId,
          retrievalId: form.value.retrievalIds,
          warehouseId: form.value.warehousingIds,
          supplierId: form.value.supplierIds,
          productSpecifications: it.productSpecifications,
          measureUnit: it.measureUnit,
          planQuantity: it.planQuantity,
          univalence: it.univalence,
          discount: it.discount,
          money: it.money,
          cost: it.cost,
          remarks: it.remarks,
        };
      });
      form.value.receiptStatus = 2;
      const reqs = { ...form.value, details };
      await savePurchaseReceipt(reqs);
      proxy.$modal.msgSuccess("采购单据审核成功");
      cancel();
    }
  });
}
function loadDetail(systematicReceipt) {
  getPurchaseOrder(systematicReceipt).then((response) => {
    option.value.warehouseId = response.data.warehousingIds;
    listWarehouse(option.value).then((response) => {
      warehouseOptions.value = response.rows;
    });
    option.value.supplierId = response.data.supplierIds;
    listSupplier(option.value).then((response) => {
      supplierOptions.value = response.rows;
    });
    optionReset();
    if (response.data.receiptStatus === 1) {
      takeEffect.value = true;
    } else if (response.data.receiptStatus === 2) {
      takeEffectBtn.value = true;
    }
    printBtn.value = false;
    finding.value = true;
    const details = response.data.details;
    const product = response.data.product;
    const map = {};
    (product || []).forEach((it) => {
      map[it.productId] = it;
    });
    form.value = {
      ...response.data,
      // 采购订单
      systematicOrderForm: response.data.systematicReceipt,
      originalOrderForm: response.data.originalReceipt,
      orderFormType: 1,
      orderFormStatus: 2,
      deliveryDate: response.data.invoiceDate,
      orderFormNotes: response.data.receiptNotes,
      orderFormAmount: response.data.totalAmount,
      orderCapitalizeAmount: response.data.capitalizeTotalAmount,
      details,
    };
    form.value.warehousingIds = Number(response.data.warehousingIds);
    form.value.retrievalIds = Number(response.data.retrievalIds);
    form.value.userIds = Number(response.data.userIds);
    form.value.supplierIds = Number(response.data.supplierIds);
  });
}
//自定义合计行
function getSummaries(param) {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }

    if (column.property !== undefined) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        if (index === 11) {
          sums[index] = Number(sums[index]).toFixed(2);
          form.value.totalAmount = sums[index];
          form.value.capitalizeTotalAmount = RMBConverter.numberToChinese(
            sums[index]
          );
        } else if (index === 12) {
          sums[index] = Number(sums[index]).toFixed(2);
        }
      } else {
        sums[index] = "";
      }
      if ([1, 2, 3, 4, 5, 6, 10].includes(index)) {
        sums[index] = "";
      }
    }
  });
  return sums;
}
// 表单重置
function reset() {
  form.value = {
    systematicReceipt: null,
    originalReceipt: null,
    receiptType: null,
    receiptCategory: 1,
    receiptStatus: 1,
    invoiceDate: getNowTime(),
    retrievalIds: null,
    warehousingIds: null,
    supplierIds: null,
    userIds: null,
    planReceipt: null,
    receiptNotes: null,
    deposit: null,
    totalAmount: null,
    capitalizeTotalAmount: null,
    findingOfAudit: null,
    reviewComments: null,
    // 采购订单
    systematicOrderForm: null,
    originalOrderForm: null,
    orderFormType: 1,
    orderFormStatus: 2,
    deliveryDate: null,
    orderFormNotes: null,
    orderFormAmount: null,
    orderCapitalizeAmount: null,
    printId: null,
    details: [],
  };
  proxy.resetForm("orderRef");
}
/** 重置操作供应商表单 */
function supplierReset() {
  supplierForm.value = {
    supplierCode: undefined,
    supplierName: undefined,
    supplierSalesPerson: undefined,
    supplierContacts: undefined,
    supplierContactNumber: undefined,
    supplierWorkAddress: undefined,
    supplierPostalCode: undefined,
    supplierOpeningDebt: undefined,
    supplierOpeningBank: undefined,
    supplierAccountNumber: undefined,
    supplierTaxId: undefined,
    supplierCompanyHomepage: undefined,
    supplierEmail: undefined,
    supplierLegalPerson: undefined,
    status: undefined,
    remarks: undefined,
  };
  proxy.resetForm("supplierRef");
}
/** 重置操作货品表单 */
function productReset() {
  productForm.value = {
    productId: undefined,
    productCode: undefined,
    productName: undefined,
    productType: undefined,
    productSpecifications: undefined,
    measureUnit: undefined,
    phonenumber: undefined,
    producer: undefined,
    costPrice: undefined,
    univalence: undefined,
    productBarcode: undefined,
    upperLimit: undefined,
    lowerLimit: undefined,
    defaultWarehouse: undefined,
    notes: undefined,
    status: "0",
  };
  proxy.resetForm("productRef");
}
// 添加货品
function addItem() {
  form.value.details.push({});
}
// 选择货品
function changeProduct(index, row) {
  form.value.details[index] = {
    productId: null,
    productCode: null,
    productName: null,
    productTypeName: null,
    productSpecifications: null,
    measureUnit: null,
    producer: null,
    inventoryQty: null,
    retrievalId: null,
    warehousingId: null,
  };
  let lists = [];
  productOptions.value.forEach((item) => {
    if (row.productCode == item.productId) {
      lists = item;
    } else if (row.productName == item.productId) {
      lists = item;
    }
  });
  form.value.details[index] = {
    systematicOrderForm: form.value.systematicOrderForm,
    systematicReceipt: form.value.systematicReceipt,
    productId: lists.productId,
    productCode: lists.productCode,
    productName: lists.productName,
    productTypeName: lists.productTypeName,
    productSpecifications: lists.productSpecifications,
    measureUnit: lists.measureUnit,
    producer: lists.producer,
    inventoryQty: lists.inventoryQty,
    retrievalId: form.value.retrievalIds,
    warehousingId: form.value.warehousingIds,
    planQuantity: 0,
    univalence: lists.univalence,
    discount: lists.discount,
    money: 0,
    cost: 0,
    remarks: null,
  };
  form.value.details = [...form.value.details];
}
/** 打印按钮 */
async function printOut() {
  form.value.printId = print_selected_files.value[1].label;
  form.value.printSize = print_selected_sizes.value[1].label;
  await viewUrl().then((res) => {
    openUrl.value = res;
  });
  const printUrl =
    openUrl.value +
    "/" +
    form.value.printId +
    "?token=Bearer " +
    getToken() +
    "&systematicReceipt=" +
    form.value.systematicReceipt +
    "&pageSize=" +
    form.value.printSize;
  window.open(printUrl, "_blank");
}
/** 删除按钮操作 */
function deleteReceipt() {
  getPurchaseOrder(form.value.systematicReceipt).then((response) => {
    const details = response.data.details;
    proxy.$modal
      .confirm(
        "确认要删除系统编号为" + form.value.systematicReceipt + "的采购单据?"
      )
      .then(function () {
        return delPurchaseReceipt(details);
      })
      .then(() => {
        proxy.$modal.msgSuccess(
          "已删除系统编号为" + form.value.systematicReceipt + "的采购单据。"
        );
        reset();
      })
      .catch(() => {});
  });
}
/** 查询货品类型下拉树结构 */
function getProductTypeTree() {
  productTypeTreeSelect().then((response) => {
    typeOptions.value = response.data;
  });
}
/** 新增供应商按钮操作 */
function supplierAdd() {
  supplierReset();
  openSupplier.value = true;
  titleSupplier.value = "新增供应商";
}
/** 提交供应商按钮 */
function submitSupplierForm() {
  proxy.$refs["supplierRef"].validate((valid) => {
    if (valid) {
      addSupplier(supplierForm.value);
      proxy.$modal.msgSuccess(
        "已新增编号为" + supplierForm.value.supplierCode + "的供应商"
      );
      openSupplier.value = false;
      listSupplier(option.value).then((response) => {
        supplierOptions.value = response.rows;
      });
    }
  });
}
/** 取消供应商按钮 */
function cancelSupplierForm() {
  openSupplier.value = false;
}
/** 新增货品按钮操作 */
function handleAdd() {
  productReset();
  getProductTypeTree();
  open.value = true;
  title.value = "添加货品";
}
/** 提交货品按钮 */
function submitProductForm() {
  proxy.$refs["productRef"].validate((valid) => {
    if (valid) {
      addProduct(productForm.value);
      proxy.$modal.msgSuccess(
        "已新增编号为" + productForm.value.productCode + "的货品"
      );
      open.value = false;
      listProduct(option.value).then((response) => {
        productOptions.value = response.rows;
      });
    }
  });
}
/** 取消货品按钮 */
function cancelProductForm() {
  open.value = false;
}
/** 重置下拉框表单 */
function optionReset() {
  option.value = {
    warehouseId: undefined,
    warehouseName: undefined,
    supplierId: undefined,
    supplierName: undefined,
    customerId: undefined,
    customerName: undefined,
    productCode: undefined,
    productName: undefined,
    pageSize: 50,
  };
}
// 查询仓库名称
function remoteWarehouse(query) {
  optionReset();
  if (query) {
    loading.value = true;
    setTimeout(() => {
      option.value.warehouseName = query;
      listWarehouse(option.value).then((response) => {
        warehouseOptions.value = response.rows;
      });
      loading.value = false;
      warehouseOptions.value = list.value.filter((item) => {
        return item.label.toLowerCase().includes(query.toLowerCase());
      });
    }, 200);
  } else {
    listWarehouse(option.value).then((response) => {
      warehouseOptions.value = response.rows;
    });
  }
}
// 查询供应商名称
function remoteSupplier(query) {
  optionReset();
  if (query) {
    loading.value = true;
    setTimeout(() => {
      option.value.supplierName = query;
      listSupplier(option.value).then((response) => {
        supplierOptions.value = response.rows;
      });
      loading.value = false;
      supplierOptions.value = list.value.filter((item) => {
        return item.label.toLowerCase().includes(query.toLowerCase());
      });
    }, 200);
  } else {
    listSupplier(option.value).then((response) => {
      supplierOptions.value = response.rows;
    });
  }
}
// 查询货品编号
function remoteProductCode(query) {
  optionReset();
  if (query) {
    loading.value = true;
    setTimeout(() => {
      option.value.productCode = query;
      listProduct(option.value).then((response) => {
        productOptions.value = response.rows;
      });
      loading.value = false;
      productOptions.value = list.value.filter((item) => {
        return item.label.toLowerCase().includes(query.toLowerCase());
      });
    }, 200);
  } else {
    listProduct(option.value).then((response) => {
      productOptions.value = response.rows;
    });
  }
}
// 查询货品名称
function remoteProductName(query) {
  optionReset();
  if (query) {
    loading.value = true;
    setTimeout(() => {
      option.value.productName = query;
      listProduct(option.value).then((response) => {
        productOptions.value = response.rows;
      });
      loading.value = false;
      productOptions.value = list.value.filter((item) => {
        return item.label.toLowerCase().includes(query.toLowerCase());
      });
    }, 200);
  } else {
    listProduct(option.value).then((response) => {
      productOptions.value = response.rows;
    });
  }
}

initialization();
getList();
</script>

<style scoped>
.form-item {
  width: 200px;
}
.footer {
  text-align: center;
}
</style>
